package main

import (
	"fmt"
	"time"
)

func main() {
	now := time.Now()
	fmt.Println(now)
	fmt.Println(now.Year())
	fmt.Println(now.Month())
	fmt.Println(now.Day())
	fmt.Println(now.Hour())
	fmt.Println(now.Minute())
	fmt.Println(now.Second())

	//时间戳
	fmt.Println(now.Unix())
	fmt.Println(now.UnixNano())

	//time.Unix()

	ret := time.Unix(now.Unix(), 0)
	fmt.Println(ret)
	fmt.Println(ret.Year())
	//时间间隔
	fmt.Println(time.Second)
	//now+1小时
	fmt.Println(now.Add(24 * time.Hour))
	fmt.Println(now.Add(10 * time.Minute))
	fmt.Println(now.Before(now.Add(24 * time.Hour)))
	fmt.Println(now.After(now.Add(24 * time.Hour)))

	//Sub表示两个时间相减
	fmt.Printf("sub===%v \n", now.Sub(now.Add(24*time.Hour)))
	nextYear, err := time.Parse("2006-01-02 15:04:00", "2022-01-04 10:50:00")
	nextYear = nextYear.UTC()
	now = now.UTC()
	fmt.Printf("nextyearsub===%v \n", now.Sub(nextYear))

	//定时器
	/* 	timer := time.Tick(5 * time.Second)
	   	for t := range timer {
	   		fmt.Println(t) //一秒钟执行一次
	   	} */

	//Y      m    d    H    M     S
	//2006   1    2    3    4     5

	//格式化时间，把语言中的时间对象  转换成字符串类型的时间
	//2022-01-03
	fmt.Println(now.Format("2006-01-02"))
	//2022/01/03 10:20:03  24进制
	fmt.Println(now.Format("2006/01/02 15:04:05"))
	//2022/01/03 11:55:02 AM
	fmt.Println(now.Format("2006/01/02 03:04:05 PM"))
	//2022/01/03 10:20:03.342
	fmt.Println(now.Format("2006/01/02 15:04:05.000"))
	//按照对应的格式把一个字符串的时间转换成时间戳
	timeObj, err := time.Parse("2006-01-02", "1990-12-07")
	if err != nil {
		fmt.Println("parse time failed,err:%v", err)
		return
	}
	fmt.Println(timeObj)
	fmt.Println(timeObj.Unix())

	//sleep
	n := 5
	fmt.Println("开始sleep  5秒！")
	time.Sleep(time.Duration(n) * time.Second)
	//time.Sleep(5 * time.Second)
	fmt.Println("结束sleep  5秒！")
	f2()

}

//时区
func f2() {
	now := time.Now() //本地的时间
	fmt.Println(now)
	//明天的这个时间
	//按照指定格式去解析一个字符串格式的时间
	time.Parse("2006-01-02 15:04:05", "2022-01-04 11:07:00")
	//按照东八区的时区和格式去解析一个字符串格式的时间
	//根据字符串加载时区
	loc, err := time.LoadLocation("Asia/Shanghai")
	if err != nil {
		fmt.Println("load loc failed,err:%v", err)
		return
	}
	timeObj, err := time.ParseInLocation("2006-01-02 15:04:05", "2022-01-04 11:07:00", loc)
	if err != nil {
		fmt.Println("parse time failed,err:%v", err)
		return
	}
	fmt.Println(timeObj)

	//时间对象相减
	td := timeObj.Sub(now)
	fmt.Println(td)
}
